package com.ohuang.demo.view

import android.animation.Animator
import android.animation.ValueAnimator
import android.app.Activity
import android.graphics.Rect
import android.util.Log
import android.view.View
import android.view.ViewGroup

/**
 *
 * 键盘弹出动画
 *  paddingView  设置需要加padding的View(一般是布局)
 *  views  需要移动的View
 *  isAnimatedCall  是否需要动画
 */
fun Activity.setKeypadAnimated(
  views: List<View>, isAnimatedCall: (Boolean) -> Boolean = {
        true
    }
) {

    window.decorView.viewTreeObserver.addOnGlobalLayoutListener {
        val r: Rect = Rect()
        window.decorView.getWindowVisibleDisplayFrame(r)
        val screenHeight: Int = window.decorView.getHeight()
        val keypadHeight: Float = screenHeight.toFloat() - r.bottom
        val decorView = window.decorView as ViewGroup
        val childAt = decorView
        if (true == childAt.getTag()) {
            childAt.setTag(null)
            return@addOnGlobalLayoutListener
        }

        if (!isAnimatedCall(keypadHeight > screenHeight * 0.15)) {
            return@addOnGlobalLayoutListener
        }
        if (keypadHeight > screenHeight * 0.15) { // 键盘显示
            val paddingTop = childAt.paddingTop
            val paddingBottom = childAt.paddingBottom
            val paddingLeft = childAt.paddingLeft
            val paddingRight = childAt.paddingRight
            childAt.setTag(true)
            childAt.setPadding(
                paddingLeft,
                paddingTop,
                paddingRight,
                (paddingBottom - keypadHeight).toInt()
            )

            val ofFloat = ValueAnimator.ofFloat(0F, keypadHeight)
            ofFloat.addUpdateListener { animation ->
                val animatedValue = animation.animatedValue as Float
                views.forEach {
                    it.translationY = -animatedValue
                }
            }
            ofFloat.setDuration(200)
            ofFloat.addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {

                }

                override fun onAnimationEnd(animation: Animator) {
                    childAt.setTag(true)
                    childAt.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
                    views.forEach {
                        it.translationY = 0F
                    }
                }

                override fun onAnimationCancel(animation: Animator) {

                }

                override fun onAnimationRepeat(animation: Animator) {

                }
            })
            ofFloat.start()
        }

    }
}